﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;

namespace Interfaz
{
    /// <summary>
    /// Interaction logic for RegistrarProducto.xaml
    /// </summary>
    public partial class RegistrarProducto : UserControl
    {
        public RegistrarProducto()
        {
            InitializeComponent();
            cargarImagen("Imagenes/d_silhouette_Bart_Simpson.jpg");
        }
        public void cargarImagen(string ruta)
        {
            BitmapImage logo = new BitmapImage();
            logo.BeginInit();
            logo.UriSource = new Uri(ruta, UriKind.Relative);
            logo.EndInit();
            image1.Source = logo;
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            if (file.ShowDialog() != null)
            {
                try
                {
                    image1.Source = GetBitmapImageFromBytes(File.ReadAllBytes(file.FileName));
                }
                catch (Exception)
                {
                    MessageBox.Show("Seleccione una imagen", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        private BitmapImage GetBitmapImageFromBytes(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                BitmapImage btm = new BitmapImage();
                btm.BeginInit();
                btm.StreamSource = ms;
                btm.CacheOption = BitmapCacheOption.OnLoad;
                btm.EndInit();
                return btm;
            }
        }
        public Byte[] BufferFromImage(BitmapImage imageC)
        {
            MemoryStream memStream = new MemoryStream();
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(imageC));
            encoder.Save(memStream);
            return memStream.GetBuffer();
        }
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Procesos.GestorRegistro.registrarProducto(textBox1.Text, textBox2.Text, BufferFromImage((BitmapImage)image1.Source));
                MessageBox.Show("Registro realizado con exito");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
